package 每日一题;

import java.util.Arrays;

/**
 * 小数尽量靠右
 * 大数尽量小
 * 对交换之后的小数后面的数组进行升序排列
 */
public class 下一个排列 {
    static StringBuffer sb=new StringBuffer();
    public static int findGreaterNum (int N) {
        // write code here
       String num=String.valueOf(N);
       int[] nums=new int[num.length()];
       for (int i=0;i<nums.length;i++){
           nums[i]=num.charAt(i);
       }
       nextPermutation(nums);

       for (int i:nums){
           sb.append(String.valueOf(i));
       }
       return Integer.valueOf(sb.toString());
    }
    public static void nextPermutation(int[] nums) {
        int i=nums.length-2;
        while (i>=0&&nums[i]>=nums[i+1]){
            i--;
        }
        if(i>=0){
            int j=nums.length-1;
            while (nums[j]<=nums[i]){
                j--;
            }
            swap(i,j,nums);


            reverse(nums,i+1);
        }else {
            Arrays.sort(nums);
        }
    }

    static void swap(int i,int j,int[] nums){
        int t=nums[i];
        nums[i]=nums[j];
        nums[j]=t;
    }
    static void reverse(int[] nums,int start){
        int left=start;
        int right=nums.length-1;
        while (left<right){
            int t=nums[left];
            nums[left]=nums[right];
            nums[right]=t;
            right--;
            left++;
        }
    }

    public static void main(String[] args) {
        int[] nums={1,3,2};
        System.out.println(findGreaterNum(12));

    }
}
